package com.spring.rechargeapi.web.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import com.google.common.collect.Lists;
import com.spera.genutil.TokenUtil;
import com.spera.shopoa.util.ShopOaSessionUtil;
import com.spera.shopoa.util.ShopOaSessionUtil.OaUser;
import com.spring.cardapi.web.dao.CardApiMapper;
import com.spring.cardapi.web.service.CardApiService;
import com.spring.common.web.dao.CommonApiMapper;
import com.spring.common.web.dao.CrmCustomerMapper;
import com.spring.common.web.model.CrmContact;
import com.spring.common.web.model.CrmCustomer;
import com.spring.common.web.service.CommonService;
import com.spring.consumebackground.web.service.ConsumeBackgroundService;
import com.spring.membercardapi.web.dao.MemberCardApiMapper;
import com.spring.membercardapi.web.requestmodel.Packages;
import com.spring.membercardapi.web.service.MemberCardApiService;
import com.spring.rechargeapi.web.dao.RechargeApiMapper;
import com.spring.rechargeapi.web.model.Application;
import com.spring.rechargeapi.web.model.ApplicationB;
import com.spring.rechargeapi.web.model.ApplyCondition;
import com.spring.rechargeapi.web.model.Card;
import com.spring.rechargeapi.web.model.CardDetail;
import com.spring.rechargeapi.web.model.Package;
import com.spring.rechargeapi.web.model.RechargeBill;
import com.spring.rechargeapi.web.model.RechargeHistory;
import com.spring.rechargeapi.web.model.RechargeRule;
import com.spring.rechargeapi.web.service.RechargeApiService;
import com.spring.security.core.context.JedisCont;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.dao.CommonMapper;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.iputil.HttpClientUtils;
import com.spring.tools.MyTools;
import com.spring.tools.Result;
import com.spring.tools.Url;
import com.spring.tools.ValidatorResultHandler;
import com.sso.api.web.dao.SsoMapper;
import com.sso.api.web.model.RequestUser;
import com.sso.api.web.model.SsoFamily;
import com.sso.api.web.model.SsoUser;
import com.spring.rechargeapi.web.requestModel.ApplicationUpdate;
@Service
public class RechargeApiServiceImpl implements RechargeApiService{
	@Resource
	private RechargeApiMapper rechargeApiMapper;
	
	@Resource
	private ConsumeBackgroundService consumeBackgroundService;
	
    @Resource
    private JedisCache jedisCache;
    
	@Resource
	private CardApiService cardApiService;
	@Resource
	private SsoMapper ssoMapper;
	@Resource
	private MemberCardApiMapper memberCardApiMapper;

	@Resource
	private MemberCardApiService memberCardApiService;
	
	@Resource
	private CommonService commonService;
	
	@Resource
	private CommonApiMapper commonApiMapper;

	@Resource
	private CrmCustomerMapper crmCustomerMapper;
	
	//充值卡优惠规则
	@Override
	public Map<String, Object> rechargeRule() {
		Map<String, Object> m = new HashMap();
		try {
			List<RechargeRule> list = rechargeApiMapper.rechargeRule();
			m.put(ApplicationUtils.DATASET, list);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "取数成功");
		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}
		return m;
	}

	
	
	
	

	/**
	 * 充值卡申请
	 * @param token
	 * @return
	 */
		@Override
		public Map<String, Object> applyCard (String token,String recharge_amount,String user_name,String identity_card,
				String phone,String apply_way_code,String rechargecard_level_code)  throws Exception{
			// TODO Auto-generated method stub
			Map<String, Object> m = new HashMap();
				
			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {

				return t;

			}

			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			try {
				
				if(!(ApplicationUtils.isNotNull(recharge_amount)&&ApplicationUtils.isNotNull(user_name)
					&&ApplicationUtils.isNotNull(identity_card)&&ApplicationUtils.isNotNull(phone)&&ApplicationUtils.isNotNull(apply_way_code)
					&&ApplicationUtils.isNotNull(rechargecard_level_code))){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "请输入必要的参数");	
					return m;
				}
				
				
				HashMap<String,Object> hm=new HashMap<String,Object>();
				hm.put("c_user_id", c_user_id);
				hm.put("recharge_amount", recharge_amount);
				hm.put("user_name", user_name);
				hm.put("identity_card", identity_card);
				hm.put("phone", phone);
				hm.put("apply_way_code", apply_way_code);
				hm.put("rechargecard_level_code", rechargecard_level_code);
				
				BigDecimal condition=rechargeApiMapper.ApplyConditionCheckCondition(rechargecard_level_code);
				
				//计算最终得到的钱
	//			BigDecimal userGetAmount=this.userGetAmount(recharge_amount);
//				hm.put("user_get_amount", userGetAmount);
				
				
				if(condition.compareTo(new BigDecimal(recharge_amount))!=-1){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "不满足申请条件");
				}
				
				
				int effect = rechargeApiMapper.applyCard(hm);
				
				if(effect!=1){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "插入失败");
					return m;
				}
				
				m.put(ApplicationUtils.STATUS, "1");
				m.put(ApplicationUtils.MSG, "取数成功");

			} catch (Exception e) {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "系统异常");
				e.printStackTrace();
			}
			return m;
		}
		
		
		
		public HashMap<String,Object> userGetAmount(String recharge_amount,String rechargeCardCategory,String type){
			HashMap<String,Object> hm=new HashMap<String,Object>();
			hm.put("recharge_amount", recharge_amount);
			hm.put("rechargeCardCategory", rechargeCardCategory);
			hm.put("type", type);
			List<HashMap<String,Object>> hmr = rechargeApiMapper.getRechargeRatio(hm);
		//	HashMap<String,Object> hmn=hmr.get(0);
		//	hmn.put("discount", new BigDecimal((String)hmn.get("discount")));
			return hmr.get(0);
		}
		
		
		
		/**
		 * 预约会员计算自己得到的金额
		 */
		@Override
		public Map<String, Object> calculateUserGetAmount (String recharge_amount,String rechargeCardCategory,String discount_type)  throws Exception{

			Map<String, Object> m = new HashMap<String, Object>();
				
			 	
				HashMap<String,Object> hm=new HashMap<String,Object>();
				hm.put("recharge_amount", recharge_amount);
				hm.put("rechargeCardCategory", rechargeCardCategory);
				hm.put("type", discount_type);
				List<HashMap<String,Object>> hmr=rechargeApiMapper.getRechargeRatio(hm);
/*				BigDecimal user_get_amount =(BigDecimal)hm2.get("userGetAmount");
				BigDecimal discount =(BigDecimal)hm2.get("discount");
				
				BigDecimal gift_amount=user_get_amount.subtract(new BigDecimal(recharge_amount));
				
				
				List<HashMap<String,Object>> list=new ArrayList<HashMap<String,Object>>();
				HashMap<String,Object> hm=new HashMap<String,Object>();
				hm.put("user_get_amount", user_get_amount);
				hm.put("gift_amount", gift_amount);
				hm.put("discount", discount);
				list.add(hm);*/
				
				m.put(ApplicationUtils.DATASET, hmr);
				m.put(ApplicationUtils.STATUS, "1");
				m.put(ApplicationUtils.MSG, "取数成功");


			return m;
		}
		
		/**
		 * 查看充值卡申请
		 */
		@Override
		public Map<String, Object> getApplicationList (String token)  throws Exception{
			// TODO Auto-generated method stub
			Map<String, Object> m = new HashMap();
				
			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {

				return t;

			}

			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			try {
				
				List<Application> list = rechargeApiMapper.getApplicationList(c_user_id);
				
				
				m.put(ApplicationUtils.DATASET, list);
				m.put(ApplicationUtils.STATUS, "1");
				m.put(ApplicationUtils.MSG, "取数成功");

			} catch (Exception e) {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "系统异常");
				e.printStackTrace();
			}
			return m;
		}
		
		/**
		 * 修改充值卡申请
		 * @param token
		 * @return
		 * @throws Exception
		 */
		@Override
	public Map<String, Object> updateApplication(String token,
			String recharge_application_id, String recharge_amount,
			String user_name, String identity_card, String phone)
			throws Exception {
	// TODO Auto-generated method stub
			Map<String, Object> m = new HashMap();
				
			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {

				return t;

			}

			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			try {
				
				int count = rechargeApiMapper.updateApplicationCheckId(recharge_application_id);
				
				if(count!=1){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "请输入能被修改的recharge_application_id");
					return m;
				}
				
				HashMap hm=new HashMap();
				hm.put("recharge_application_id", recharge_application_id);
				hm.put("recharge_amount", recharge_amount);
				hm.put("user_name", user_name);
				hm.put("identity_card", identity_card);
				hm.put("phone", phone);
				
				
				int effect=rechargeApiMapper.updateApplication(hm);
				
				m.put(ApplicationUtils.STATUS, "1");
				m.put(ApplicationUtils.MSG, "修改成功");

			} catch (Exception e) {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "系统异常");
				e.printStackTrace();
			}
			return m;
		}
		
		
		
		
		
		@Override
		public Map<String, Object> cancelApplication(String token,
				String recharge_application_id, String cancel_reason)
				throws Exception {
		// TODO Auto-generated method stub
				Map<String, Object> m = new HashMap();
					
				Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
				if (t != null) {

					return t;

				}

				String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
				
				try {
					
					HashMap hmc=MyTools.checkIsNotNull(recharge_application_id);
					if(ApplicationUtils.isNotNull(hmc)){
						return m;
					}
					
					
					int count = rechargeApiMapper.updateApplicationCheckId(recharge_application_id);
					
					if(count!=1){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "请输入能被取消的recharge_application_id");
						return m;
					}
					
					HashMap hm=new HashMap();
					hm.put("recharge_application_id", recharge_application_id);
					hm.put("cancel_reason", cancel_reason);
					
					
					
					int effect=rechargeApiMapper.cancelApplication(hm);
					
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "取消成功");

				} catch (Exception e) {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "系统异常");
					e.printStackTrace();
				}
				return m;
			}
		
		
		
		/**
		 * 查看自己有的充值卡
		 * @param token
		 * @return
		 * @throws Exception
		 */
		@Override
		public Map<String, Object> getCardList(String token,String rechargecard_id)
				throws Exception {
		// TODO Auto-generated method stub
				Map<String, Object> m = new HashMap();
					
				Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
				if (t != null) {

					return t;

				}

				String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
				
				try {
					
					HashMap hm=new HashMap();
					hm.put("rechargecard_id", rechargecard_id);
					hm.put("c_user_id", c_user_id);
					
					List<Card> list = rechargeApiMapper.getCardList(hm);
					
					m.put(ApplicationUtils.DATASET, list);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "查询成功");

				} catch (Exception e) {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "系统异常");
					e.printStackTrace();
				}
				return m;
			}
		
		
		
		
		@Override
		public Map<String, Object> checkOutCreateBill(String token,String rechargecard_id,String custom_amount,
				String business_type_code,String kids_park_id,String comment,String payment_way_code)
				throws Exception {
		// TODO Auto-generated method stub
				Map<String, Object> m = new HashMap();
					
				Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
				if (t != null) {

					return t;
					
				}

				String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
				

					
					
					HashMap hmc=MyTools.checkIsNotNull(rechargecard_id,custom_amount,business_type_code,kids_park_id,payment_way_code);
					if(ApplicationUtils.isNotNull(hmc)){
						return m;
					}
					
					
				/*	BigDecimal  balance= rechargeApiMapper.checkOutCheckBalance(rechargecard_id);
					
					System.out.println("balance"+balance);
					
					if(balance==null){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "rechargecard_id无效");
						return m;
					}
					
					if(balance.compareTo(new BigDecimal(custom_amount))==-1){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "余额不足");
						return m;
					}
					
					
					HashMap hm=new HashMap();
					hm.put("custom_amount", custom_amount);
					hm.put("rechargecard_id", rechargecard_id);
					
					
					int effect= rechargeApiMapper.checkOutUpdateBalance(hm);
					
					if(effect!=1){
						throw new Exception();
					}*/
					
					
					/*HashMap hm2=new HashMap();
					hm2.put("c_user_id", c_user_id);
					hm2.put("rechargecard_id", rechargecard_id);
					hm2.put("custom_amount", custom_amount);
					
					int effect2 =rechargeApiMapper.checkOutInsertJournalAccount(hm2);
					
					
					if(effect2!=1){
						throw new Exception();
					}
					*/
					String uuid=ApplicationUtils.randomUUID();
					
					
					HashMap hm3=new HashMap();
					hm3.put("c_user_id", c_user_id);
					hm3.put("business_type_code", business_type_code);
					hm3.put("custom_amount", custom_amount);
					hm3.put("comment", comment);
					hm3.put("payment_way_code", payment_way_code);
					hm3.put("kids_park_id", kids_park_id);
					hm3.put("rechargecard_id", rechargecard_id);
					hm3.put("uuid", uuid);
					
					
					
					int effect3 =rechargeApiMapper.checkOutInsertConsumeHis(hm3);
					
					if(effect3!=1){
						throw new Exception();
					}
					
					HashMap hmx=new HashMap();
					hmx.put("card_consume_his_id", uuid);
					
					ArrayList al=new ArrayList();
					al.add(hmx);
					
					m.put(ApplicationUtils.DATASET, al);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "查询成功");

				
				return m;
			}
		
		
		
		@Override
		public Map<String, Object> checkOut(String token, String card_consume_his_id, String rechargecard_id, 
				String amount) throws Exception {
		// TODO Auto-generated method stub
				Map<String, Object> m = new HashMap();
					
				Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
				if (t != null) {

					return t;
					
				}

				String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
				

					
					
					HashMap hmc=MyTools.checkIsNotNull(rechargecard_id,card_consume_his_id,amount);
					if(ApplicationUtils.isNotNull(hmc)){
						return m;
					}
					
					HashMap hm=new HashMap();
					hm.put("card_consume_his_id", card_consume_his_id);
					hm.put("rechargecard_id", rechargecard_id);
					hm.put("amount", amount);
					hm.put("c_user_id", c_user_id);
					
					//得到余额
					BigDecimal  balance= rechargeApiMapper.checkOutCheckBalance(rechargecard_id);
					
					//得到订单还需要支付多少钱
					BigDecimal  needPay= rechargeApiMapper.checkOutCheckNeedPay(hm);
					
					
					
					System.out.println("balance"+balance);
					
					if(balance==null){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "rechargecard_id无效");
						return m;
					}
					
					
					//验证余额是否充足
					if(balance.compareTo(new BigDecimal(amount))==-1){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "余额不足");
						return m;
					}
					
					//得到如果支付完成后订单状态
					int status=needPay.compareTo(new BigDecimal(amount));
					int pay_status_code=0;
					
					if(status==0){
						pay_status_code=2;
					}
					if(status==1){
						pay_status_code=1;
					}
					
					hm.put("pay_status_code", pay_status_code);

					
					
					//修改余额
					int effect= rechargeApiMapper.checkOutUpdateBalance(hm);
					
					if(effect!=1){
						throw new Exception();
					}
					
					
				
					//插入流水表
					int effect2 =rechargeApiMapper.checkOutInsertJournalAccount(hm);
					
					
					if(effect2!=1){
						throw new Exception();
					}
					
					//修改订单状态
					int effect3=rechargeApiMapper.checkOutUpdateConsumeHis(hm);
					
					if(effect3!=1){
						throw new Exception();
					}
					
					//修改
					int effect4=rechargeApiMapper.checkOutInsertConsumePayHis(hm);
					
					if(effect4!=1){
						throw new Exception();
					}
					
					
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "插入成功");

				
				return m;
			}
		
		
		
		
		
		/**
		 * 查看充值卡流水表
		 */
		@Override
		public Map<String, Object> getRechargeBillList(String token,String rechargecard_id,String page_size,
				String page_index,String skip,String rows)
				throws Exception {
		// TODO Auto-generated method stub
				Map<String, Object> m = new HashMap();
					
				Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
				if (t != null) {

					return t;

				}

				String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
				
				try {
					
					
					if(!ApplicationUtils.isNotNull(rechargecard_id)){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "请输入必要的参数");
						return m;
					}
					
					
					
					int pagesize=20;
					int pageindex=1;
					int skipint=0;
					int rowsint=20;
					
					if(page_size!=null&&page_index!=null){
						
						 pagesize=Integer.parseInt(page_size);
						 pageindex=Integer.parseInt(page_index);
						
						skipint=pagesize*(pageindex-1);
						rowsint=pagesize;
						
					}else if(skip!=null&&rows!=null){
						
						 skipint=Integer.parseInt(skip);
						 rowsint=Integer.parseInt(rows);
						
					}
					
					
					HashMap hm=new HashMap();
					hm.put("rechargecard_id", rechargecard_id);
					hm.put("skip", skipint);
					hm.put("rows", rowsint);
					
					List<RechargeBill> list = rechargeApiMapper.getRechargeBillList(hm);
					
					m.put(ApplicationUtils.DATASET, list);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "查询成功");

				} catch (Exception e) {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "系统异常");
					e.printStackTrace();
				}
				return m;
			}
		
	
		
		
		/**
		 * 查看充值卡充值历史
		 */
		@Override
		public Map<String, Object> getRechargeHistory(String token,String rechargecard_id,String page_size,
				String page_index,String skip,String rows)
				throws Exception {
		// TODO Auto-generated method stub
				Map<String, Object> m = new HashMap();
					
				Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
				if (t != null) {

					return t;

				}

				String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
				
				try {
					
					
					if(!ApplicationUtils.isNotNull(rechargecard_id)){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "请输入必要的参数");
						return m;
					}
					
					HashMap hm=MyTools.pageIndexToSkip(page_size, page_index, skip, rows);
					
					hm.put("rechargecard_id", rechargecard_id);
					
					
					List<RechargeHistory> list = rechargeApiMapper.getRechargeHistory(hm);
					
					m.put(ApplicationUtils.DATASET, list);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "查询成功");

				} catch (Exception e) {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "系统异常");
					e.printStackTrace();
				}
				return m;
			}
			
		
		
		/**
		 * 查看本卡有哪些可以购买的套餐
		 */
		@Override
		public Map<String, Object> getPackageList(String token,String kids_park_id,String rechargecard_id,String page_size,
				String page_index,String skip,String rows)
				throws Exception {
		// TODO Auto-generated method stub
				Map<String, Object> m = new HashMap();
					
				Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
				if (t != null) {

					return t;

				}

				String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
				
				try {
					
					
					if(!ApplicationUtils.isNotNull(rechargecard_id)){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "请输入必要的参数");
						return m;
					}
					
					
					
					HashMap hm=MyTools.pageIndexToSkip(page_size, page_index, skip, rows);
					
					hm.put("rechargecard_id", rechargecard_id);
					hm.put("kids_park_id", kids_park_id);
					
					List<Package> list = rechargeApiMapper.getPackageList(hm);
					
					m.put(ApplicationUtils.DATASET, list);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "查询成功");

				} catch (Exception e) {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "系统异常");
					e.printStackTrace();
				}
				return m;
			}
		
		
		
		/**
		 * 购买课程套餐
		 */
	@Override
	public Map<String, Object> buyPackage(String token, String rechargecard_id,
			String package_id, String c_family_member_id, String comment,String baby_name)
				throws Exception {
		// TODO Auto-generated method stub
				Map<String, Object> m = new HashMap();
					
				Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
				if (t != null) {

					return t;

				}
				System.out.println("buyPackage");

				String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
				
				try {
					
					HashMap hmc=MyTools.checkIsNotNull(rechargecard_id,package_id,c_family_member_id,baby_name);
					if(!ApplicationUtils.isNotNull(hmc)){
						return hmc;
					}
					
					
					String uuid=ApplicationUtils.randomUUID();
					
					HashMap hm=new HashMap();
					hm.put("c_user_id", c_user_id);
					hm.put("rechargecard_id", rechargecard_id);
					hm.put("package_id", package_id);
					hm.put("c_family_member_id", c_family_member_id);
					hm.put("comment", comment);
					hm.put("uuid", uuid);
					hm.put("baby_name", baby_name);
					
					
					//验证卡号
					int count=rechargeApiMapper.buyPackageCheckCardId(hm);
					if(count!=1){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "请输入有效的rechargecard_id");
						return m;
					}
					
					//检验余额
					BigDecimal banlance = rechargeApiMapper.buyPackageCheckBalance(hm);
					if(banlance.compareTo(new BigDecimal(0))==-1){
						m.put(ApplicationUtils.STATUS, "0");
						m.put(ApplicationUtils.MSG, "余额不足");
						return m;
					}
					//扣除余额
					int effect=rechargeApiMapper.buyPackageUpdateBalance(hm);
					
					if(effect!=1){
						throw new Exception();
					}
					//插入消费卡明细表
					int effect2=rechargeApiMapper.buyPackageInsertCardDetail(hm);
					
					if(effect2<=0){
						throw new Exception();
					}
					//插入消费卡课程明细表
					int effect3=rechargeApiMapper.buyPackageInsertCardCourseDetail(hm);
					
					if(effect3<=0){
						throw new Exception();
					}
					
					//插入消费明细表
					int effect4=rechargeApiMapper.buyPackageInsertConsumeHis(hm);
					
					if(effect4<=0){
						throw new Exception();
					}
					
					

					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "查询成功");

				} catch (Exception e) {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "系统异常");
					e.printStackTrace();
				}
				return m;
			}
		
	
	
	
	
	
	/**
	 *查看自己的核心业务
	 */
	@Override
	public Map<String, Object> getCardDetailList(String token,String rechargecard_id,String c_family_member_id)
			throws Exception {
	// TODO Auto-generated method stub
			Map<String, Object> m = new HashMap();
				
			Map<String, Object> t = TokenUtil.checkToken(token,jedisCache);
			if (t != null) {

				return t;

			}

			String c_user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			
			try {
				
				HashMap hmc=MyTools.checkIsNotNull(rechargecard_id);
				if(!ApplicationUtils.isNotNull(hmc)){
					return hmc;
				}
				
				
				HashMap hm=new HashMap();
				hm.put("card_id", rechargecard_id);
				hm.put("c_family_member_id", c_family_member_id);
				
				List<CardDetail> list = rechargeApiMapper.getCardDetailList(hm);
				
				m.put(ApplicationUtils.DATASET, list);
				m.put(ApplicationUtils.STATUS, "1");
				m.put(ApplicationUtils.MSG, "查询成功");

			} catch (Exception e) {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "系统异常");
				e.printStackTrace();
			}
			return m;
		}
	
	
	
	@Override
	public Map<String, Object> getApplyCondition() throws Exception {
	// TODO Auto-generated method stub
			Map<String, Object> m = new HashMap();
				
			try {
				
				List<ApplyCondition> list = rechargeApiMapper.getApplyCondition();
				
				m.put(ApplicationUtils.DATASET, list);
				m.put(ApplicationUtils.STATUS, "1");
				m.put(ApplicationUtils.MSG, "查询成功");

			} catch (Exception e) {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "系统异常");
				e.printStackTrace();
			}
			return m;
		}
	
	@Override
	public Map<String, Object> applyCardBackground  (String point,String rechargeCardCategory,String phone, String family_phone, String address, String zipcode, String recharge_amount,
			 String apply_way_code, 
			 String auditor_id, String auditor_name,String desc,String operater_id, String operater_name, String consume_recommend_id,
				String consume_recommend_name,String kids_park_id,List<Map<String,Object>> babies,List<Map<String,Object>> guardians,String apply_type,
				String consume_recommend_deptID,String consume_recommend_dept_name,String InitialOperatorID
				 ,String InitialOperatorName,String earnestMoney,String discount_type,HttpServletRequest request)  throws Exception{
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap();
		List<Map<String,Object>> blist = Lists.newArrayList();		
		try {
			OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
			if(oaUser==null){
				
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请先登录");
				return m;		
			}
			
			InitialOperatorID=oaUser.getOa_user_id();
			InitialOperatorName=oaUser.getOa_user_name();
			
			String real_name=null;
			String identity_cardm=null;
			
			HashMap hmc=MyTools.checkIsNotNull(phone,apply_way_code
				,apply_type,rechargeCardCategory);
			if(hmc!=null){
				return hmc;
			}
			if(point==null||point.equals("0")){
				point="0";
			}
			
			if(earnestMoney==null||earnestMoney.equals("")){				
				earnestMoney="0";
			}
			
			String c_familyID=null;
			String c_user_id=null;
			
/*			if(new BigDecimal(recharge_amount).compareTo(new BigDecimal(earnestMoney))==-1){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "定金不能大于总金额");
				return m;															
			}*/
			
			
			// 注册用户
			if (apply_type.equals("1")) {

				if (babies != null) {

					// 验证宝宝参数
					for (int i = 0; i < babies.size(); i++) {
						Map<String, Object> jsonObject2 = (Map<String, Object>) babies
								.get(i);

						String baby_name2 = String.valueOf(jsonObject2.get("name"));
						String baby_sex_code2 = String.valueOf(jsonObject2.get("sex_code"));
						String baby_birthday2 = String.valueOf(jsonObject2.get("birthday"));
						String memeber_name = String.valueOf(jsonObject2.get("member_name"));

						HashMap hmcc2 = MyTools.checkIsNotNull(baby_name2,
								baby_birthday2, baby_sex_code2, memeber_name);
						if (hmcc2 != null) {
							return hmcc2;
						}

					}

				}
	
			RequestUser ru=new RequestUser();
			ru.setPhone(phone);
			
			//guardians.size();
			boolean temp=false;
			
			CrmCustomer crmCustomer=new CrmCustomer();	
			
			CrmContact crmContact=new CrmContact();	
			
			for(Map<String,Object> jsonObject:guardians){

				String phone3 = (String) jsonObject.get("phone");
				String identity_card = (String) jsonObject.get("identity_card");
				String name = (String) jsonObject.get("name");					
				String member_name = (String) jsonObject.get("member_name");
				String role_id = (String) jsonObject.get("role_id");
				String email = (String) jsonObject.get("email");
				String companyName = (String) jsonObject.get("companyName");

				
				if(phone3.equals(phone)){
					temp=true;
					
					real_name=name;
					
					identity_cardm=identity_card;
					
					ru.setIdentity_card(identity_card);
					ru.setReal_name(name);
					ru.setMember_name(member_name);
					ru.setC_role_id(role_id);
					ru.setUserName(phone);
					ru.setAddress(address);
					ru.setEmail(email);
					ru.setCompanyName(companyName);		
					ru.setAdmission_way_id("1");
					ru.setKids_parkID(kids_park_id);
					
					crmCustomer.setCustomername(name);
					crmCustomer.setKidsParkid(kids_park_id);
					crmCustomer.setInitialoperatorid(InitialOperatorID);
					crmCustomer.setInitialoperatorname(InitialOperatorName);
					crmCustomer.setRecommenderid(consume_recommend_id);
					crmCustomer.setRecommendername(consume_recommend_name);
					crmCustomer.setRecommenderdeptid(consume_recommend_deptID);
					crmCustomer.setRecommenderdeptname(consume_recommend_dept_name);
					crmCustomer.setDesc(desc);
					crmCustomer.setBusinessTypesid("d9ec62a7-283c-4770-bac4-b156aa6aee12");
					crmCustomer.setResponserdeptid(oaUser.getUser_dept_id());
					crmCustomer.setResponserdeptname(oaUser.getUser_dept_name());
					
					crmContact.setName(name);
					crmContact.setPhonenumber(phone3);
					crmContact.setEmail(email);
					crmContact.setIsmaincontact(1);
					crmContact.setCompanyname(companyName);
					crmContact.setCertificatenumber(identity_card);
					crmContact.setRoleid(role_id);
					crmContact.setDesc(desc);
					crmContact.setInitialoperatorid(InitialOperatorID);
					crmContact.setInitialoperatorname(InitialOperatorName);
				}
				
				
				HashMap hmcc=MyTools.checkIsNotNull(name,member_name,role_id);
				if(hmcc!=null){
					return hmcc;
				}
							
			};
			
			//验证主手机号是否
			if(temp==false){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "合同手机号必须是监护人手机号之一");
				return m;
			}
		
		//	String address,String zipcode
			
			ru.setFamily_address(address);
			ru.setZipcode(zipcode);
			ru.setFamily_phone(family_phone);
			
			crmContact.setHomephone(family_phone);
			crmContact.setPostcode(zipcode);
			//发起请求用于注册主账号
			Map<String, Object> hm=cardApiService.addUser(ru,request);
			
			if(!hm.get(ApplicationUtils.STATUS).equals("1")){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, hm.get(ApplicationUtils.MSG));
				return m;
			}
			
			
			HashMap<String,Object>  hm2=(HashMap<String,Object>)hm.get(ApplicationUtils.DATASET);
			 c_familyID=String.valueOf(hm2.get("c_familyID"));
			 c_user_id=String.valueOf(hm2.get("c_user_id"));
			 
			 crmContact.setCuserid(c_user_id);
			 
			 crmCustomer.getCrmContact().add(crmContact);
			
			//注册其他监护人账号
			for(Map<String,Object> jsonObject:guardians){
			//	JSONObject jsonObject = json2.getJSONObject(i);
				RequestUser ru1=new RequestUser();
				
				String phone3 = (String) jsonObject.get("phone");
				if(!phone3.equals(phone)){
					
					String identity_card = (String) jsonObject.get("identity_card");
					String name = (String) jsonObject.get("name");					
					String member_name = (String) jsonObject.get("member_name");
					String role_id = (String) jsonObject.get("role_id");
					String email = (String) jsonObject.get("email");
					String companyName = (String) jsonObject.get("companyName");
					
					ru1.setC_family_id(c_familyID);												
					ru1.setIdentity_card(identity_card);
					ru1.setReal_name(name);											
					ru1.setMember_name(member_name);
					ru1.setC_role_id(role_id);						
					ru1.setUserName(phone);
					ru1.setPhone(phone3);
					ru1.setEmail(email);
					ru1.setCompanyName(companyName);
					ru1.setAdmission_way_id("1");
					ru1.setKids_parkID(kids_park_id);
					
					Map<String, Object> hm3=cardApiService.addUser(ru1,request);						
					if(!hm3.get(ApplicationUtils.STATUS).equals("1")){
						throw new Exception();
					}
					HashMap<String,Object>  hm4=(HashMap<String,Object>)hm3.get(ApplicationUtils.DATASET);
					 c_familyID=String.valueOf(hm4.get("c_familyID"));
					 c_user_id=String.valueOf(hm4.get("c_user_id"));
					
					 	
					crmContact.setName(name);
					crmContact.setPhonenumber(phone3);
					crmContact.setEmail(email);
					crmContact.setIsmaincontact(0);
					crmContact.setCompanyname(companyName);
					crmContact.setCertificatenumber(identity_card);
					crmContact.setRoleid(role_id);
					crmContact.setDesc(desc);
					crmContact.setInitialoperatorid(InitialOperatorID);
					crmContact.setInitialoperatorname(InitialOperatorName);
					crmContact.setHomephone(family_phone);
					crmContact.setPostcode(zipcode);
					crmContact.setCuserid(c_user_id);
					 
					crmCustomer.getCrmContact().add(crmContact);
				}
			}
			commonService.addCustomer(crmCustomer);
			//注册宝宝账号
			if (babies != null) {
			for(Map<String,Object> jsonObject:babies){
				//	JSONObject jsonObject = json2.getJSONObject(i);
				if(!ApplicationUtils.isNotNull(ApplicationUtils.Object2String(jsonObject.get("c_user_id")))){
					RequestUser ru1=new RequestUser();
					String baby_name = String.valueOf(jsonObject.get("name"));
					String baby_sex_code = String.valueOf(jsonObject.get("sex_code")) ;					
					String baby_birthday = String.valueOf(jsonObject.get("birthday"));
					String member_name = String.valueOf(jsonObject.get("member_name"));
					ru1.setC_family_id(c_familyID);							
					ru1.setReal_name(baby_name);
					ru1.setUserName(ApplicationUtils.randomUUID());
					ru1.setMember_name(member_name);
					ru1.setSex_code(baby_sex_code);
					ru1.setBirthday(baby_birthday);
					ru1.setC_role_id("0");
					ru1.setAdmission_way_id("1");
					ru1.setKids_parkID(kids_park_id);
					
					Map<String, Object> hm3=cardApiService.addUser(ru1,request);

					if(!hm3.get(ApplicationUtils.STATUS).equals("1")){
							throw new Exception();
					}
					//System.out.println(((HashMap<String,Object>)hm3.get(ApplicationUtils.DATASET)).get("c_user_id"));
					jsonObject.put("c_user_id", ((HashMap<String,Object>)hm3.get(ApplicationUtils.DATASET)).get("c_user_id"));
				}
				blist.add(jsonObject);
			}
		}
	}else if(apply_type.equals("2")){
		HashMap hm=new HashMap();
		hm.put("phone", phone);
		hm.put("isAll", 1);
		List<HashMap> list= ssoMapper.getIDsByPhone(hm);
		
		if(list.size()<1){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "使用该手机注册的家庭不存在");
			return m;
		}
		
		
		HashMap hp=new HashMap();
		hp.put("c_family_id", list.get(0).get("c_family_id"));
		hp.put("family_phone",family_phone );
		hp.put("address",address);
		hp.put("zipcode",zipcode);

	//	c_family_id
		int effectn=ssoMapper.updateFamily(hp);
	
		HashMap hmr=list.get(0);
		
		for(HashMap user:list){
			if(user.get("card_number")!=null){
				c_familyID=String.valueOf(hmr.get("c_family_id"));
				c_user_id=String.valueOf(hmr.get("c_user_id"));
				real_name=String.valueOf(hmr.get("real_name"));
			}
		}
		
		//c_user_id=ssoFamily.g
		
	}else{
		m.put(ApplicationUtils.STATUS, "0");
		m.put(ApplicationUtils.MSG, "请输入有效的apply_type");
		return m;
		
	}

			
			String	uuid=ApplicationUtils.randomUUID();
	
			HashMap hm=new HashMap();
			hm.put("uuid",uuid);	
			hm.put("c_user_id", c_user_id);
			hm.put("recharge_amount", recharge_amount);
			hm.put("user_name", real_name);
			hm.put("identity_card", identity_cardm);
			hm.put("phone", phone);
			hm.put("apply_way_code", apply_way_code);			
			hm.put("auditor_id", auditor_id);
			hm.put("auditor_name", auditor_name);
			hm.put("desc", desc);
			hm.put("operater_id", operater_id);
			hm.put("operater_name", operater_name);
			hm.put("consume_recommend_id", consume_recommend_id);
			hm.put("consume_recommend_name", consume_recommend_name);
			hm.put("kids_park_id", kids_park_id);
			hm.put("point", point);
		
			hm.put("consume_recommend_deptID", consume_recommend_deptID);
			hm.put("consume_recommend_dept_name", consume_recommend_dept_name);
			hm.put("InitialOperatorID", InitialOperatorID);
			hm.put("InitialOperatorName", InitialOperatorName);
			
			hm.put("earnestMoney", earnestMoney);
			
			//普通充值类型
			if(rechargeCardCategory.equals("1")){
				//计算最终得到的钱
				HashMap hm4=this.userGetAmount(recharge_amount,rechargeCardCategory,"0");
				BigDecimal user_get_amount =new BigDecimal((Double)hm4.get("userGetAmount"));
				BigDecimal discount =(BigDecimal)hm4.get("discount");
				
			//	BigDecimal userGetAmount=this.userGetAmount(recharge_amount);
				hm.put("user_get_amount", user_get_amount);
				if(discount_type==null||discount_type.equals("0")){
					hm.put("discount", discount);
				}else{
					hm.put("discount", 1);
				}
				
			}else if(rechargeCardCategory.equals("2")){
				//打折卡充值类型
				HashMap<String,Object> hmp=new HashMap<String,Object>();
				hmp.put("recharge_amount", recharge_amount);
				hmp.put("rechargeCardCategory", rechargeCardCategory);		
				
				List<HashMap<String,Object>> list=rechargeApiMapper.getRechargeRatio(hmp);
				HashMap<String,Object> hmr=list.get(0);
				BigDecimal discount=(BigDecimal)hmr.get("discount") ;
				
				hm.put("user_get_amount", 0);
				hm.put("discount", discount);
			}else{
				//内部员工打卡
				HashMap<String,Object> hmp=new HashMap<String,Object>();
				hmp.put("recharge_amount", 0);
				hmp.put("rechargeCardCategory", rechargeCardCategory);		
				
				//HashMap hmr=rechargeApiMapper.getRechargeRatio(hmp);
				BigDecimal discount=new  BigDecimal(0.75);//(BigDecimal)hmr.get("discount") ;				
				hm.put("user_get_amount", 0);
				hm.put("discount", discount);
				hm.put("recharge_amount", 0);
				point="0";				
				hm.put("point", point);
				
			}
		
			
			hm.put("rechargeCardCategory", rechargeCardCategory);
			
			
//			BigDecimal condition=rechargeApiMapper.ApplyConditionCheckCondition(rechargecard_level_code);
//			
//			if(condition==null){
//				m.put(ApplicationUtils.STATUS, "0");
//				m.put(ApplicationUtils.MSG, "该卡没有开放申请");
//				return m;
//			}
//			
//			if(condition.compareTo(new BigDecimal(recharge_amount))!=-1){
//				m.put(ApplicationUtils.STATUS, "0");
//				m.put(ApplicationUtils.MSG, "不满足申请条件");
//				return m;
//			}
			
			
			int effect = rechargeApiMapper.applyCardBackground(hm);
			
			if(effect!=1){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "插入失败");
				return m;
			}
			
			HashMap<String,Object> hmx=new HashMap<String,Object>();
			hmx.put("applicationID", uuid);
			System.out.println(uuid);
			//插入合同宝宝关联表
			for(Map<String,Object> jsonObject:blist){
				jsonObject.put("applicationID", uuid);
				jsonObject.put("InitialOperatorID", InitialOperatorID);
				jsonObject.put("InitialOperatorName", InitialOperatorName);
				memberCardApiMapper.insertContractBabys(jsonObject);
			}
		
//			HashMap<String,Object> hmx=new HashMap<String,Object>();
//			hmx.put("applicationID", uuid);			
			
			m.put(ApplicationUtils.DATASET, hmx);
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "申请成功");

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}
		return m;
	}
	
	@Override
	public Object updateapply(ApplicationUpdate application,BindingResult result,
			HttpServletRequest request) throws Exception  {
			
			Map<String, Object> m = new HashMap();	

			Map<String, Object> ContractMap = new HashMap();
			
			Result retVal = ValidatorResultHandler.handle(result);
			if("0".equalsIgnoreCase(retVal.getStatus())){
				return retVal;
			}

			RequestUser mainGuardian=null;
			for(RequestUser guardian:application.getGuardians()){

				MyTools.checkIsNotNull(guardian.getC_user_id());
				if(application.getPhone().equals(guardian.getPhone())){
					mainGuardian=guardian;
				}
				
				guardian.setC_family_id(application.getC_family_id());
				Map<String,Object> hm3=cardApiService.addUser(guardian,request);
				if(hm3.get(ApplicationUtils.STATUS).equals("0")){
					return hm3;
				}
			}

			for(RequestUser baby:application.getBabies()){
				MyTools.checkIsNotNull(baby.getC_user_id());
				
				baby.setC_family_id(application.getC_family_id());
				baby.setC_role_id("0");

				Map<String,Object> hm3=cardApiService.addUser(baby,request);
				
				if(hm3.get(ApplicationUtils.STATUS).equals("0")){
					return hm3;
				}
			}
			
			int effect=ssoMapper.updateFamily3(application);
			if(effect<1){					
//				m.put(ApplicationUtils.STATUS, "0");
//				m.put(ApplicationUtils.MSG, "");
//				return m;
			}
			application.setUser_name(mainGuardian.getReal_name());
			application.setIdentity_card(mainGuardian.getIdentity_card());
			
			String rechargeCardCategory=application.getRechargeCardCategory();
			String recharge_amount=application.getRecharge_amount();
			//普通充值类型
			if(rechargeCardCategory.equals("1")){
				//计算最终得到的钱
				HashMap hm4=this.userGetAmount(recharge_amount,rechargeCardCategory,"0");
				BigDecimal user_get_amount =new BigDecimal((Double)hm4.get("userGetAmount"));
				BigDecimal discount =(BigDecimal)hm4.get("discount");

				application.setUserGetAmount(user_get_amount.toString());
				application.setDiscount(discount.toString());

			}else if(rechargeCardCategory.equals("2")){
				//打折卡充值类型
				HashMap<String,Object> hmp=new HashMap<String,Object>();
				hmp.put("recharge_amount", recharge_amount);
				hmp.put("rechargeCardCategory", rechargeCardCategory);	
				
				List<HashMap<String,Object>> list=rechargeApiMapper.getRechargeRatio(hmp);
				HashMap<String,Object> hmr=list.get(0);
				BigDecimal discount=(BigDecimal)hmr.get("discount") ;
				
				application.setUserGetAmount("0");
				application.setDiscount(discount.toString());
			}else{
				//内部员工打卡
				HashMap<String,Object> hmp=new HashMap<String,Object>();
				hmp.put("recharge_amount", 0);
				hmp.put("rechargeCardCategory", rechargeCardCategory);		

				application.setUserGetAmount("0");
				application.setDiscount("0.75");
				application.setRecharge_amount("0");
				application.setPoint("0");

			}
					
			int effect3=rechargeApiMapper.updateApplication2(application);

			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "修改成功");
			return m;
	}

	
	@Override
	public Map<String, Object> applyCardPayment(String c_recharge_applicationID,String payment_amount,
			String card_number,String card_out_number,String contract_name,String begin_time,String end_time,String file,
			String OperatorID,String OperatorName,int hasPackage,String contractID,String orderID,String totalDueAmount,
			String earnestMoney,String discount_type) throws Exception{
		Map<String, Object> m = new HashMap();
		
		if(card_number!=null&&card_number.equals("")){
			card_number=null;
		}
		if(card_number!=null&&card_number.equals("null")){
			card_number=null;
		}
		
		if(card_out_number!=null&&card_out_number.equals("")){
			card_out_number=null;
		}
		if(card_out_number!=null&&card_out_number.equals("null")){
			card_out_number=null;
		}
						
		HashMap hmc=MyTools.checkIsNotNull(c_recharge_applicationID);
		if(hmc!=null){
			return hmc;
		}	
		
		HashMap hm = new HashMap();
		hm.put("c_recharge_applicationID", c_recharge_applicationID);
		hm.put("card_out_number", card_out_number);
		hm.put("card_number", card_number);
		
		int count2=rechargeApiMapper.checkApplicationID(hm);
		System.out.println(c_recharge_applicationID);
		if(count2==0){
		//	throw new Exception();
		    m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "该申请id无效");
			return m;
		}

		HashMap ApplicationContent = rechargeApiMapper.getApplicationContent(hm);

		String c_user_id=String.valueOf(ApplicationContent.get("c_user_id"));
		String total_amount=String.valueOf(ApplicationContent.get("total_amount"));
		String kids_parkID=String.valueOf(ApplicationContent.get("kids_parkID"));
		String rechargeCardCategory=MyTools.ObjectToString(ApplicationContent.get("rechargeCardCategory"));
		String paid_amount=MyTools.ObjectToString(ApplicationContent.get("paid_amount"));
		

		//生成卡内吗
		SsoUser ssoUser=ssoMapper.getUserByID(c_user_id);
		if(ssoUser.getCard_number()==null&&card_number==null&&rechargeCardCategory.equals("3")){
			card_number=ApplicationUtils.randomUUID();
			card_out_number=ApplicationUtils.randomUUID();
		}
		
		//验证是否绑定会员卡
		if((!(card_number==null||card_number.equals("")))&&(ssoUser.getCard_number()!=null&&!ssoUser.getCard_number().equals(""))){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "该用户已经绑定了会员卡无需再绑定会员卡");
			return m;
		}
		
		if(card_number!=null){
			int count3= rechargeApiMapper.checkCardNumber(hm);
			if(count3>=1){
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "该卡已被使用");
				return m;
			}
			
		}
/*		else if(ssoUser.getCard_number()==null&&card_number==null){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "该用户还没有绑定请输入充值卡");
			throw new Exception();
			//return m;
		}*/

		//检验实际支付
		if(payment_amount==null){
			payment_amount=total_amount;
		}
		float payment_amountf=Float.valueOf(payment_amount);
		float total_amountf=Float.valueOf(total_amount);
/*		if(payment_amountf>total_amountf){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "实际支付不能超过总金额");
			return m;
		}*/
		
		
		//产生order_detail
		List<HashMap> order_detail=new ArrayList();
		HashMap order_detailObject=new HashMap();
		order_detailObject.put("business_type_code", 101+"");
		order_detailObject.put("unit_code", 7+"");
		order_detailObject.put("amount", total_amount+"");
		order_detailObject.put("quantity", 1+"");
		
		hm.put("kids_parkID", kids_parkID);
		

		String[] order_product_kids_park_ids = rechargeApiMapper.getOrderProductKidsParkID(hm);
		if(order_product_kids_park_ids.length<1){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "充值卡商品没有被维护，请联系后台维护充值卡商品");
			return m;	
		}
		String order_product_kids_park_id=order_product_kids_park_ids[0];
		
		
		//String order_product_kids_park_id=String.valueOf(OrderProduct.get("order_product_kids_park_id"));
		
		order_detailObject.put("order_product_kids_park_id", order_product_kids_park_id);
		
		order_detail.add(order_detailObject);
		
		//产生order_payment
		List<HashMap> order_payment=new ArrayList();
		HashMap order_paymentObject=new HashMap();
		order_paymentObject.put("payment_way_code", 3+"");
		order_paymentObject.put("amount", total_amount+"");
		
		order_payment.add(order_paymentObject);
		
		String order_paymentStr=order_payment.toString();
		if(orderID!=null){
			order_paymentStr="[]";
		}
		//产生订单
		Map<String, Object> checkOutReturn=consumeBackgroundService.
				checkOut(null,null,orderID,c_user_id,null, kids_parkID, total_amount, payment_amount, "购买充值卡",null, order_detail.toString(), order_paymentStr,0,null,null,null,null);
		//得到反馈
		String costatus=String.valueOf(checkOutReturn.get(ApplicationUtils.STATUS)); 
		String comsg= String.valueOf(checkOutReturn.get(ApplicationUtils.MSG));
		HashMap<String, Object> codataset= (HashMap<String, Object>)checkOutReturn.get(ApplicationUtils.DATASET);
		
		orderID=String.valueOf(codataset.get("orderID"));
		
		if(costatus.equals("0")){
			return checkOutReturn;
		}

		
		String real_name=ssoMapper.selectRealNameByID(c_user_id);
		//得到各个必要的参数
		HashMap afterPayPara=ApplicationContent;
		
		
		//如果已经有会员卡了卡号用旧的卡号
		if(card_number==null){
			card_number=ssoUser.getCard_number();
			card_out_number=ssoUser.getCard_out_number();
		}
	
		
		//生成会员码
		HashMap KidsAndRegion=memberCardApiMapper.getKidsAndRegion(afterPayPara);
		String index=String.valueOf(KidsAndRegion.get("index"));
		String areaCode=String.valueOf(KidsAndRegion.get("areaCode"));
		
		afterPayPara.put("index", index);
		afterPayPara.put("areaCode", areaCode);
		
		String count=rechargeApiMapper.getRechargeCount(afterPayPara);			
		if(index.length()==1){
			index="0"+index;
		};			
		
		Date d=new Date();
		SimpleDateFormat sFormat = new SimpleDateFormat("yy");
		String year=sFormat.format(d);
		
		String recharge_number=areaCode+index+"2"+year+count;
		
		if(rechargeCardCategory.equals("3")){
			recharge_number="s"+recharge_number;
		}
		
		
		
		afterPayPara.put("recharge_number", recharge_number);
		afterPayPara.put("order_product_kids_park_id", order_product_kids_park_id);
		afterPayPara.put("card_number", card_number);
		afterPayPara.put("card_out_number", card_out_number);
		afterPayPara.put("user_name", real_name);
		
		String rechargecardID=ApplicationUtils.randomUUID();
		afterPayPara.put("rechargecardID", rechargecardID);
		
		afterPayPara.put("contract_name", contract_name);
		afterPayPara.put("begin_time", begin_time);
		afterPayPara.put("end_time", end_time);
		
		
		
		//生成会员号
		//得到注册数
//		String count=rechargeApiMapper.getMemberCount(afterPayPara);
//		//count++;
//		
//		String card_level_code=String.valueOf(ApplicationContent.get("card_level_code"));
//		
//		if(card_level_code.length()==1){
//			card_level_code="0"+card_level_code;
//		}
//		
//		if(index.length()==1){
//			index="0"+index;
//		};
//		
//		
//		Date d=new Date();
//		SimpleDateFormat sFormat = new SimpleDateFormat("yy");
//		String year=sFormat.format(d);
//		
//		String member_number=areaCode+index+"1"+card_level_code+year+count;
		
		String crmCustomerID=commonApiMapper.getCrmCustomerID(c_user_id);
		
		CrmCustomer cc=new CrmCustomer();
		cc.setId(crmCustomerID);
		cc.setServicestage(2);		
		crmCustomerMapper.updateByPrimaryKeySelective(cc);
		
/*		if(!(hasPackage==1)){
			
		String contractStatus="1";
			
		if(paid_amount.equals("0")){
			contractStatus="2";
		}			
			
		//插入合同
		HashMap ic=afterPayPara;
		ic.put("contractTypeCode", 4);
		ic.put("contractNumber", recharge_number);
		ic.put("name", contract_name);
		ic.put("desc", "");
		ic.put("beginTime", begin_time);
		ic.put("endTime", end_time);
		ic.put("InitialOperatorID", OperatorID);
		ic.put("InitialOperatorName", OperatorName);
		ic.put("partA", real_name);
		ic.put("kids_parkID", kids_parkID);
		ic.put("crmCustomerID", crmCustomerID);
		ic.put("phone", ssoUser.getPhone());
		ic.put("amount", total_amount);
		ic.put("earnestAmount", paid_amount);
		ic.put("contractStatus", contractStatus);
		ic.put("totalDueAmount", totalDueAmount);
		
		Map<String, Object> r= cardApiService.insertContract(ic);
		r.get(ApplicationUtils.STATUS);
		if(r.get(ApplicationUtils.STATUS).equals("0")){
			throw new Exception();
		}
		
		HashMap hm5=(HashMap)r.get(ApplicationUtils.DATASET);
		
		contractID=String.valueOf(hm5.get("contractID"));
		
		afterPayPara.put("contractID", contractID);					

		if(file!=null&&!file.equals("")){
			Map<String, Object> cm=cardApiService.insertFile(file, contractID);
			}
		}else{
			afterPayPara.put("contractID", contractID);				
		}*/
		
		afterPayPara.put("contractID", contractID);
		afterPayPara.put("InitialOperatorID", OperatorID);
		afterPayPara.put("InitialOperatorName", OperatorName);
		afterPayPara.put("OperatorID", OperatorID);
		afterPayPara.put("OperatorName", OperatorName);
	

		if(new BigDecimal(paid_amount).compareTo(new BigDecimal("0"))==0){
			afterPayPara.put("EntityAvailableState", 10);
		}else{
			afterPayPara.put("EntityAvailableState", 2);	
		}	
		
		//插入充值卡卡表
		int effect2=rechargeApiMapper.insertRechargecard(afterPayPara);
		if(effect2==0){
			throw new Exception();
		}

		
		String MemberNumber=ssoUser.getMember_number();//  ssoMapper.getMemberByID(hm2);
		
		//修改用户表
		
		HashMap<String ,Object> hm2=new HashMap<String ,Object>();
		hm2.put("c_user_id", c_user_id);
		hm2.put("kids_park_id", kids_parkID);
		
		if(MemberNumber==null||MemberNumber.equals("")){
			String count4=memberCardApiMapper.getDistinctMemberCount(kids_parkID);
			
			String sso_member_number=areaCode+index+year+count4;
			
			if(rechargeCardCategory.equals("3")){
				sso_member_number="s"+sso_member_number;
			}
			
			
			hm2.put("member_number", sso_member_number);
			hm2.put("card_number", card_number);
			hm2.put("card_out_number", card_out_number);
			hm2.put("member_type", "1");
			
			int effect=ssoMapper.updateUserNumber(hm2);
				
			if(effect<1){
				throw new Exception();
			}
			int effect3= ssoMapper.updateUserFamilyNumber(hm2);
			if(effect3<1){
				throw new Exception();
			}
		}
		afterPayPara.put("orderID", orderID);
		
		int effect4=rechargeApiMapper.rewriteApplication(afterPayPara);
		
		if(effect4==0){
			throw new Exception();
		}
		
		String point=String.valueOf(ApplicationContent.get("point"));
		

		Map<String, Object> updatePointmap= cardApiService.updatePoint(c_user_id, "3", point, "1", "购买充值卡");
		System.out.println(updatePointmap.toString());

		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "插入成功");
		
		
		return m;
	}
	
		
	
	
	@Override
	public Map<String, Object> getApplicationByID(String applicationID) throws Exception {
	// TODO Auto-generated method stub
			Map<String, Object> m = new HashMap();

	
	
		if(!ApplicationUtils.isNotNull(applicationID)){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请输入必要的参数");
			return m;
		}
		HashMap hm=new HashMap();
		hm.put("applicationID", applicationID);
		
		List<ApplicationB> list = rechargeApiMapper.getApplicationByID(hm);
		
		if(list.size()>0){
			ApplicationB application=list.get(0);
			
			String phone=MyTools.ObjectToString(application.getPhone());
			Map<String, Object> ssoFamilym=memberCardApiService.getFamilyDetail(phone, null, null);
			List<SsoFamily> ssoFamily=(List<SsoFamily>)ssoFamilym.get(ApplicationUtils.DATASET);
			application.setSsoFamily(ssoFamily);
	
		}
	
		m.put(ApplicationUtils.DATASET, list);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "查询成功");

			return m;
		}

		// 检查token
				private Map<String, Object> checkToken(String token) {
					Map<String, Object> s = new HashMap<String, Object>();
					if (!ApplicationUtils.isNotNull(token)) {
						s.put(ApplicationUtils.STATUS, "0");
						s.put(ApplicationUtils.MSG, "请先登录");
						return s;
					} else {
						if (!jedisCache.exists(token)) {
							s.put(ApplicationUtils.STATUS, "-9999");
							s.put(ApplicationUtils.MSG, "用户登录已失效，请先重新登录");
							return s;
						} else {
							jedisCache.expire(token, JedisCont.JEDIS_EXPRISE);
							return null;
						}
					}
				}
}
